<template>
  <AppBar source-path="/index/book" :title="`${route.query.id ? '编辑':'新增'}` + '书签'"/>
  <div class="book-form-wrapper">
    <var-form ref="formRef" scroll-to-error="start">
      <var-space direction="column" :size="[14, 0]">
        <var-input
          clearable
          placeholder="请输入网址"
          :rules="[(v) => !!v || '网址不能为空']"
          v-model="formData.url"
        />
        <var-input
          clearable
          placeholder="请输入名称"
          :rules="[(v) => !!v || '名称不能为空']"
          v-model="formData.name"
          class="mt1"
        />
      </var-space>
      <var-uploader
        :rules="[(v) => !!formData.src || '至少上传一张图片']"
        @after-read="afterRead"
        :maxlength="1"
        class="mt1"
      >
        <div class="upload-box">
          <var-icon name="plus" class="icon" v-if="!formData.src" />
          <img :src="imageBase + formData.src" v-else />
        </div>
      </var-uploader>
      <var-button block type="info" class="btn" @click="handleSave">
        触发验证
      </var-button>
    </var-form>
  </div>
  <var-snackbar :type="showMsgRef.type" v-model:show="showMsgRef.visible">{{
    showMsgRef.type === 'success' ? '操作成功！' : '操作失败！'
  }}</var-snackbar>
</template>
<script setup>
import { reactive, ref, inject, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Snackbar } from '@varlet/ui';
import useSymbols from '../../compostions/useSymbols';
import AppBar from '../../components/AppBar/index.vue';
import { uploadFileApi } from '../../apis/uploadApi';

const imageBase = import.meta.env.VITE_BASE_FILE_SRC;

const { addItem, updateInfoItem, getInfoById } = inject(useSymbols);

const router = useRouter();
const route = useRoute();

const formData = reactive({
  url: '',
  name: '',
  src: '',
});
const formRef = ref(null);
const idRef = ref();
const showMsgRef = ref({
  visible: false,
  type: 'success',
});

onMounted(() => {
  if (route.query.id) {
    idRef.value = route.query.id;
    getInfoById(idRef.value).then((res) => {
      console.log(res);
      formData.url = res.url;
      formData.name = res.title;
      formData.src = res.screenshot;
    });
  }
});

// 获取文件后上传到指定接口
const afterRead = (varFile) => {
  uploadFileApi(varFile.file).then((res) => {
    formData.src = res;
  });
};

// 保存
const handleSave = async () => {
  const bool = await formRef.value.validate();
  if (bool) {
    const param = {
      title: formData.name,
      titleEn: '',
      screenshot: formData.src,
      url: formData.url,
    };
    try {
      if (idRef.value) {
        await updateInfoItem({ ...param, id: idRef.value });
      } else {
        await addItem(param);
      }
      showMsgRef.value.visible = true;
      setTimeout(() => {
        router.back();
      }, 400);
    } catch (error) {
      showMsgRef.value.visible = true;
      showMsgRef.value.type = warning;
    }
  }
};
</script>
<style scoped lang="less">
.book-form-wrapper {
  padding: 1rem;

  .upload-box {
    width: calc(100vw - 2rem);
    height: 7rem;
    border: 1px dashed #aaa;
    border-radius: 0.8rem;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    .icon {
      font-size: 1.5rem;
    }
    img {
      width: 100%;
    }
  }
  .mt1 {
    margin-top: 1rem;
  }
  .btn {
    margin-top: 3rem;
    background-color: var(--system-primary-color);
  }
  /deep/.var-form-details__extra-message {
    display: none;
  }
}
</style>
